import { ApiResponse } from '@/type/http'
import axios, {
  type AxiosInstance,
  type AxiosRequestConfig,
  type AxiosResponse,
  type InternalAxiosRequestConfig,
} from 'axios'
import {
  ElNotification,
  ElMessageBox,
  ElMessage,
  ElLoading,
} from 'element-plus'
// 定义接口返回数据的结构
interface ResponseData<T = any> {
  errCode: number
  data: T
  msg: string
}

class HttpClient {
  private instance: AxiosInstance
  public downloadLoadingInstance: any
  constructor(config: AxiosRequestConfig) {
    this.instance = axios.create(config)

    // 请求拦截器
    this.instance.interceptors.request.use(
      (config: InternalAxiosRequestConfig) => {
        // 在这里可以添加token等
        this.downloadLoadingInstance = ElLoading.service({
          lock: true,
          text: '处理中，请稍候...',
          background: 'rgba(0, 0, 0, 0.7)',
          target: document.getElementById('loading-container'),
        })
        const token = localStorage.getItem('token')
        if (token) {
          config.headers.Authorization = `Bearer ${token}`
        }
        return config
      },
      (error: any) => {
        return Promise.reject(error)
      }
    )

    // 响应拦截器
    this.instance.interceptors.response.use(
      (response: AxiosResponse<ResponseData>) => {
        // debugger
        // const { errCode, data, msg } = response.data
        this.downloadLoadingInstance.close()
        return response.data
        // 根据业务状态码处理
        // if (errCode === 200) {

        // } else {
        //   // 可以在这里统一处理错误
        //   ElNotification.error({ title: msg })
        //   return Promise.reject(new Error(msg || 'Error'))
        // }
      },
      (error: any) => {
        this.downloadLoadingInstance.close()
        // 处理HTTP错误状态码
        if (error.response?.status === 401) {
          // token过期处理
          ElNotification.error({ title: '请求路径错误' })
        }
        return Promise.reject(error)
      }
    )
  }

  // 封装请求方法
  public request<T = any>(config: AxiosRequestConfig): Promise<T> {
    return this.instance.request(config)
  }

  public get<T = any, R = ApiResponse<T>>(
    url: string,
    config?: AxiosRequestConfig
  ): Promise<R> {
    return this.instance.get(url, config)
  }

  public post<T = any, R = ApiResponse<T>>(
    url: string,
    data?: any,
    config?: AxiosRequestConfig
  ): Promise<R> {
    return this.instance.post(url, data, config)
  }
}

// 创建实例
const http = new HttpClient({
  baseURL: import.meta.env.VITE_API_BASE_URL, // 从环境变量获取
  timeout: 10000,
})

export default http
